import Axios from 'axios'

const HTTP = (store, router) => {
  const instance = Axios.create({
    baseURL: 'http://127.0.0.1:8001/sell',
    timeout: 10000,
    timeoutErrorMessage: '连接超时',
    headers: {
      "accept": "application/json",
      "content-type": "application/json"
    }
  });

  instance.interceptors.request.use(config => {
    const token = store.state.token;
    if (token) {
      config.headers.common['Bearer'] = token;
    } else if (!token && router.currentRoute.path !== '/login') {
      router.replace({
        path: 'login'
      })
    }

    return config;
  }, error => Promise.reject(error));

  instance.interceptors.response.use(config => {
    switch (config.data.code) {
      case 1001:
        localStorage.removeItem('token');
        store.state.token = '';
        router.replace({
          path: 'login'
        });
        break;
    }
    return config
  })

  return instance
}

export default HTTP;
